<script setup lang="ts">
import { computed, shallowRef, watch } from 'vue';
import type { SelectProps } from 'ant-design-vue';
import type { DataNode } from 'ant-design-vue/es/tree';
import { $t } from '@/locales';
import { fetchGetAllPages, fetchGetMenuTree, fetchGetRoleMenus, fetchUpdateRoleMenus } from '@/service/api';
import { useRouteStore } from '@/store/modules/route';

defineOptions({
  name: 'MenuAuthModal'
});

interface Props {
  /** the roleId */
  roleId: number;
}

const props = defineProps<Props>();

const visible = defineModel<boolean>('open', {
  default: false
});

const routeStore = useRouteStore();

function closeModal() {
  visible.value = false;
}

const title = computed(() => $t('common.edit') + $t('page.manage.role.menuAuth'));

const home = shallowRef('');

async function getHome() {
  home.value = 'home';
}

async function updateHome(val: SelectProps['value']) {
  // request

  home.value = val as string;
}

const pages = shallowRef<string[]>([]);

async function getPages() {
  const { error, data } = await fetchGetAllPages();

  if (!error && data && Array.isArray(data)) {
    pages.value = data;
  } else {
    pages.value = [];
  }
}

const pageSelectOptions = computed(() => {
  const opts: CommonType.Option[] = pages.value.map(page => ({
    label: page,
    value: page
  }));

  return opts;
});

const tree = shallowRef<DataNode[]>([]);

async function getTree() {
  const { error, data } = await fetchGetMenuTree();

  if (!error) {
    tree.value = recursiveTransform(data);
  }
}

function recursiveTransform(data: Api.SystemManage.MenuTree[]): DataNode[] {
  return data.map(item => {
    const key = String(item.id);
    const menuTitle = (item as any).menuName; // 临时用类型断言

    if (item.children) {
      return {
        key,
        title: menuTitle,
        children: recursiveTransform(item.children)
      };
    }

    return {
      key,
      title: menuTitle
    };
  });
}

const checks = shallowRef<string[]>([]); // 改为字符串数组

// 递归获取所有树节点的key
function getAllTreeKeys(treeData: DataNode[]): string[] {
  const keys: string[] = [];

  function traverse(node: DataNode) {
    keys.push(node.key as string);
    if (node.children) {
      node.children.forEach(traverse);
    }
  }

  treeData.forEach(traverse);
  return keys;
}

async function getChecks() {
  try {
    const { error, data } = await fetchGetRoleMenus(props.roleId);
    if (!error && data && Array.isArray(data)) {
      // 将数字数组转换为字符串数组
      const roleMenuIds = data.map(id => String(id));

      // 获取树中所有存在的key
      const existingKeys = getAllTreeKeys(tree.value);

      // 只保留存在于树中的key
      checks.value = roleMenuIds.filter(key => existingKeys.includes(key));
    } else {
      checks.value = [];
    }
  } catch (error) {
    console.error('获取角色菜单权限失败:', error);
    checks.value = [];
  }
}

async function handleSubmit() {
  try {
    console.log('开始提交菜单权限...');
    console.log('角色ID:', props.roleId);

    // 将字符串数组转换回数字数组
    const menuIds = checks.value.map(key => Number.parseInt(key, 10));
    const { error } = await fetchUpdateRoleMenus(props.roleId, menuIds);

    if (!error) {
      console.log('更新成功');
      window.$message?.success?.($t('common.modifySuccess'));

      // 重新加载动态菜单以刷新左侧菜单栏
      try {
        await routeStore.initAuthRoute();
        console.log('动态菜单重新加载成功');
      } catch (menuError) {
        console.error('重新加载动态菜单失败:', menuError);
      }

      closeModal();
    } else {
      console.error('更新失败:', error);
      window.$message?.error?.('操作失败');
    }
  } catch (error) {
    console.error('更新角色菜单权限失败:', error);
    window.$message?.error?.('操作失败');
  }
}

async function init() {
  getHome();
  getPages();
  await getTree();
  await getChecks();
}

watch(visible, val => {
  if (val) {
    init();
  }
});
</script>

<template>
  <AModal v-model:open="visible" :title="title" class="w-480px">
    <div class="flex-y-center gap-16px pb-12px">
      <div>{{ $t('page.manage.menu.home') }}</div>
      <ASelect :value="home" :options="pageSelectOptions" class="w-240px" @update:value="updateHome" />
    </div>
    <ATree v-model:checked-keys="checks" :tree-data="tree" checkable :height="280" class="h-280px" />
    <template #footer>
      <AButton size="small" class="mt-16px" @click="closeModal">
        {{ $t('common.cancel') }}
      </AButton>
      <AButton type="primary" size="small" class="mt-16px" @click="handleSubmit">
        {{ $t('common.confirm') }}
      </AButton>
    </template>
  </AModal>
</template>

<style scoped></style>
